
import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:wanxiang_app/bean/kan_count_entity.dart';
import 'package:wanxiang_app/bean/login_entity.dart';
import 'package:wanxiang_app/pages/home/qa.dart';
import 'package:wanxiang_app/pages/home/tousu.dart';
import 'package:wanxiang_app/pages/my/collections.dart';
import 'package:wanxiang_app/pages/my/invite.dart';
import 'package:wanxiang_app/pages/my/ordersBuy.dart';
import 'package:wanxiang_app/pages/my/priceBuyer.dart';
import 'package:wanxiang_app/pages/my/priceMy.dart';
import 'package:wanxiang_app/pages/my/profile.dart';
import 'package:wanxiang_app/pages/my/realName.dart';
import 'package:wanxiang_app/pages/my/realName_copy.dart';
import 'package:wanxiang_app/pages/my/records.dart';
import 'package:wanxiang_app/pages/my/wallet.dart';
import 'package:wanxiang_app/utils/constant.dart';
import 'package:wanxiang_app/utils/user_util.dart';
import '../../bean/order_list_entity.dart';
import '../../utils/network_manager.dart';
import '../../utils/network_url.dart';
import '../../utils/tabChangeEvent.dart';
import '../../utils/toast_util.dart';
import '../../widgets/myappbar.dart';
import 'package:get/get.dart';
import 'package:event_bus/event_bus.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'goodsList.dart';
import 'ordersSell.dart';
import 'package:badges/badges.dart' as badges;

class MyController extends GetxController  with StateMixin{
  @override
  void onInit()  {
    super.onInit();
       _getService();
    tabbarEventBus.on<TabChangedEvent>().listen((event) {
      if(event.tabIndex==4){
        _sellList();
        _buyList();
        _messageLog();
        update();
      }
    });
    _sellList();
    _buyList();
    _messageLog();
  }
  @override
  void onClose() {
    super.onClose();
  }

  @override
  void onReady() {
    super.onReady();
  }

  late LoginData data;
  bool isInital = false;
   _getService() {
    DioManager.getInstance().post(ServiceUrl.myInfo,{
      "user_name":UserUtil.getUSER()?.userName
    }, (data1) async {
      var map = jsonDecode(data1);
      LoginEntity  entity = LoginEntity.fromJson(map);
      data = entity.data;
      isInital = true;
      var map2 = map['data'];
      UserUtil.saveUSER2(jsonEncode(map2).toString());
      update();

    }, (error) {
      ToastUtil.show(error);
    });
  }

// 根据身份证号获取年龄
  String getAgeFromCardId(String cardId) {
    if(cardId.trim().isEmpty){
      return '已满18周岁';
    }
    int len = (cardId.trim() + "").length;
    String strBirthday = "";
    if (len == 18) {  //处理18位的身份证号码从号码中得到生日和性别代码
      strBirthday = cardId.substring(6, 10) + "-" + cardId.substring(10, 12) + "-" + cardId.substring(12, 14);
    }
    if (len == 15) {
      strBirthday = "19" + cardId.substring(6, 8) + "-" + cardId.substring(8, 10) + "-" + cardId.substring(10, 12);
    }
    int age = getAgeFromBirthday(strBirthday);
    if(age>=18){
      return '已满18周岁';
    }
    return '未满18周岁';
  }

// 根据出生日期获取年龄
  int getAgeFromBirthday(String strBirthday) {
    if(strBirthday == null || strBirthday.isEmpty) {
      print('生日错误');
      return 0;
    }
    DateTime birth = DateTime.parse(strBirthday);
    DateTime now = DateTime.now();

    int age = now.year - birth.year;
    //再考虑月、天的因素
    if (now.month < birth.month || (now.month == birth.month && now.day < birth.day)) {
      age --;
    }
    return age;
  }

  String getShortName(String name){
    if(name.isEmpty){
      return '';
    }
    String aa = '';
    for(int i = 1;i<name.length;i++){
      aa=aa+"*";
    }
    return name.substring(0,1)+aa;
  }
  List<OrderListData> buyList = [];
   int buyingCount = 0;
  void _buyList(){
    DioManager.getInstance().post(ServiceUrl.orderList,{
      "user_name": UserUtil.getUSER()?.userName,
    }, (data) async {
      OrderListEntity bannerEntity = OrderListEntity.fromJson(jsonDecode(data));
      buyList = bannerEntity.data;
      buyingCount = 0;
      for(var item in bannerEntity.data){
        if(item.status == 13 || item.status == 12){
          buyingCount++;
        }
      }
      update();
    }, (error) {
      ToastUtil.show(error);
    });
  }
  int sellingCount = 0;
  void _sellList(){
    sellingCount=0;
    print('_sellList_sellList_sellList');
    DioManager.getInstance().post(ServiceUrl.myGoodsList,{
      "user_name":UserUtil.getUSER()?.userName.toString()
    }, (data) async {
      OrderListEntity bannerEntity = OrderListEntity.fromJson(jsonDecode(data));
      for(var item in bannerEntity.data){
        if(item.status == 13 || item.status == 12 || item.status == 11){
          sellingCount++;
        }
      }

      update();
    }, (error) {
      ToastUtil.show(error);
    });
  }

  int buyNum = 0;
  int myNum = 0;
  void _messageLog(){
    DioManager.getInstance().post(ServiceUrl.getMessageLogCount,{
      "user_name":UserUtil.getUSER()?.userName.toString()
    }, (data) async {
      KanCountEntity bannerEntity = KanCountEntity.fromJson(jsonDecode(data));
      buyNum = int.parse( bannerEntity.buyNum);
      myNum = int.parse( bannerEntity.myNum);
      update();
    }, (error) {
      ToastUtil.show(error);
    });
  }

}


class MyPage extends GetView<MyController> {

  late MyController controller ;
  late BuildContext context ;
  @override
  Widget build(BuildContext context1) {
    Get.lazyPut<MyController>(() => MyController());

    controller = Get.find();
    context = context1;
    return GetBuilder<MyController>(
      builder: (_){
        return  Scaffold(
            appBar: MyAppBar(context: context, title: '我的'),
            backgroundColor: Colors.white,
            body:_content());
      },
    );
  }

  Widget _content(){
    return !controller.isInital?Container():
    SingleChildScrollView(
      child:    Container(
        padding: EdgeInsets.only(left: 16.w,right: 16.w,top: 0,bottom: 20.h),
        child: Column(
          children: [
            _top(),
            SizedBox(height: 22.h,),
            _orderSell(),
            _line(),
            _orderBuy(),
            _line(),
            _other()
          ],
        ),
      )
    )

 ;
  }
  Widget _top(){
    return Container(
      width: MediaQuery.of(context).size.width - 32.w,
      height: 104.h,
        decoration:  BoxDecoration(
            borderRadius: BorderRadius.circular(8.r),
            gradient: const LinearGradient(      //渐变位置
                begin: Alignment.centerLeft, //右上
                end: Alignment.centerRight, //左下
                //渐变颜色[始点颜色, 结束颜色]
                colors: [Color(0xFFF1F6FF), Color(0xFFF9F5F4),Color(0xFFEFFCFA)]
            )
        ),
      child:  Row(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          ClipOval(
            child: controller.data.userPhoto.isEmpty?
            Image.asset('${Constant.IMG_BASE}me_default.png',width: 56.w,height: 56.w,fit: BoxFit.cover):

            CachedNetworkImage(imageUrl: controller.data.userPhoto, imageBuilder: (context, imageProvider) => Container(
                height: 56.w,
                width: 56.w,
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  image: DecorationImage(
                    image: imageProvider,
                    fit: BoxFit.cover,
                  ),
                )))
          )
          ,
          SizedBox(width: 5.w,),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(controller.data.nickname,style: TextStyle(
                color: Color(0xFF333333),
                fontSize: 14.sp
              ),),
              Text( 'ID:'+controller.data.userId.toString()  ,style: TextStyle(
                  color: const Color(0xFF666666),
                  fontSize: 11.sp
              ),),
              Text(  controller.data.idCard.trim().isEmpty?'未实名认证':'已实名认证',style: TextStyle(
                  color: const Color(0xFFFF0000),
                  fontSize: 11.sp
              ),),

            ],
          ),
          SizedBox(width: 10.w,),

          Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Row(
                children: [
                  InkWell(
                      onTap: (){
                        Get.to(()=>WalletPage(),preventDuplicates:false);
                      },
                      child: Container(
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                              color: Colors.white,
                              borderRadius: BorderRadius.circular(17.r)
                          ),
                          width: 60.w,
                          height: 34.h,
                          child: Text('钱包')
                      )
                  )
                  ,
                  SizedBox(width: 20.w,),
                  InkWell(
                      onTap: (){
                        Get.to(()=>ProfilePage(),preventDuplicates:false)?.then((value) => {
                          controller._getService()
                        });
                      },
                      child: Container(
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                              color: Colors.white,
                              borderRadius: BorderRadius.circular(17.r)
                          ),
                          width: 60.w,
                          height: 34.h,
                          child: Text('设置')
                      )
                  )
                ],
              ),
              SizedBox(height: 10.w,),
              Text( controller.getShortName(controller.data.realName) + controller.getAgeFromCardId(controller.data.idCard)  ,style: TextStyle(
                  color: const Color(0xFF666666),
                  fontSize: 13.sp
              ),),

            ],
          )

   ,
        ],
      ),
    );
  }

  Widget _orderBuy(){
    return Column(
      children: [
        SizedBox(height: 8.h,),
        _part('我买的'),
        SizedBox(height: 21.h,),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            _orderItem(Constant.IMG_BASE+'me_waitpay.png','待支付',1),
            _orderItem(Constant.IMG_BASE+'me_ing.png','交易中',2),
            _orderItem(Constant.IMG_BASE+'me_cancel.png','已取消',3),
            _orderItem(Constant.IMG_BASE+'me_deal.png','已成交',4),
            _orderItem(Constant.IMG_BASE+'me_refund.png','已退款',5),
          ],
        )
      ],
    );
  }

  Widget _orderSell(){
    return Column(
      children: [
        _part('我卖的'),
        SizedBox(height: 21.h,),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            _orderItem2(Constant.IMG_BASE+'order_sell_wait.png','审核中',1),
            _orderItem2(Constant.IMG_BASE+'order_sell_shell.png','已上架',2),
            _orderItem2(Constant.IMG_BASE+'order_sell_ing.png','交易中',3),
            _orderItem2(Constant.IMG_BASE+'order_sell_deal.png','已成交',4),
            _orderItem2(Constant.IMG_BASE+'order_sell_fail.png','审核失败',5),
          ],
        )
      ],
    );
  }

  Widget _part(name){
    return Container(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Row(
            children: [
              Container(
                width: 4.w,
                height: 16.h,
                color: Color(0xFF007BE5),
              ),
              SizedBox(width: 8.w,),
              Text(name,style: TextStyle(
                  color: Color(0xFF333333),
                  fontWeight: FontWeight.bold,
                  fontSize: 15.sp
              ),)
            ],
          ),
          name=='我卖的' ||  name=='我买的'?
          InkWell(
              onTap: (){
                if(name=='我卖的'){
                  Get.to(()=>OrdersSellPage(),arguments: 0,preventDuplicates:false);
                }else{
                  Get.to(()=>OrdersBuyPage(),arguments: 0,preventDuplicates:false);
                }

              },
              child:   Text('全部>>',style: TextStyle(
                  color: Color(0xFF666666),
                  fontSize: 13.sp
              ),)
          )
              :Container()
        ],
      )
    ) ;
  }

  Widget _orderItem2(img,name,status){
    return (name=='交易中' &&  controller.sellingCount>0)? badges.Badge(
      badgeContent: Text(
        controller.sellingCount.toString(),
        style:
        TextStyle(color: Colors.white, fontSize: 12.sp),
      ),
      child:     InkWell(
        onTap: (){
          Get.to(()=>OrdersSellPage(),arguments: status,preventDuplicates:false)?.then((value) => controller._sellList());
        },
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Image.asset(img,width: 20.w,height: 20.h,),
            SizedBox(height: 8.h,),
            Text(name,style: TextStyle(
                color: Color(0xFF333333),
                fontSize: 13.sp
            ),)
          ],
        )
        ,
      ),
    ):

     InkWell(
      onTap: (){
        Get.to(()=>OrdersSellPage(),arguments: status,preventDuplicates:false);
      },
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Image.asset(img,width: 20.w,height: 20.h,),
          SizedBox(height: 8.h,),
          Text(name,style: TextStyle(
              color: Color(0xFF333333),
              fontSize: 13.sp
          ),)
        ],
      )
      ,
    ) ;
  }

  Widget _orderItem(img,name,status){
  return  (name=='交易中' &&  controller.buyingCount>0)? badges.Badge(
      badgeContent: Text(
        controller.buyingCount.toString(),
        style:
        TextStyle(color: Colors.white, fontSize: 12.sp),
      ),
      child:    InkWell(
        onTap: (){
          Get.to(()=>OrdersBuyPage(),arguments: status,preventDuplicates:false)?.then((value) => controller._buyList());
        },
        child:
        Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Image.asset(img,width: 20.w,height: 20.h,),
            SizedBox(height: 8.h,),
            Text(name,style: TextStyle(
                color: Color(0xFF333333),
                fontSize: 13.sp
            ),)
          ],
        )
        ,
      ) ,
    ):
     InkWell(
      onTap: (){
        Get.to(()=>OrdersBuyPage(),arguments: status,preventDuplicates:false);
      },
      child:
      Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Image.asset(img,width: 20.w,height: 20.h,),
          SizedBox(height: 8.h,),
          Text(name,style: TextStyle(
              color: Color(0xFF333333),
              fontSize: 13.sp
          ),)
        ],
      )
      ,
    ) ;
  }

  Widget _line(){
    return Container(
      margin: EdgeInsets.only(top: 20.h),
      height: 3.h,
      width: MediaQuery.of(context).size.width - 46.w,
      color: Color(0xFFF5F5F5),
    );
  }

  Widget _other(){
    return Column(
      children: [
        SizedBox(height: 12.h,),
        _part('其他'),
        SizedBox(height: 21.h,),

        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Stack(
              children: [
                _otherItem(Constant.IMG_BASE+'me_me_kanjian.png','我的砍价'),
                controller.myNum>0?
                Positioned(child: Container(width: 12.w,height: 12.w,decoration: BoxDecoration(
                  shape: BoxShape.circle,color: Color(0xFFFF0000),
                ),),
                right: 0,top: 0,):Container()
              ],
            )
            ,

            Stack(
              children: [
                _otherItem(Constant.IMG_BASE+'me_kanjia.png','买家砍价'),
                controller.buyNum>0?
                Positioned(child: Container(width: 12.w,height: 12.w,decoration: BoxDecoration(
                  shape: BoxShape.circle,color: Color(0xFFFF0000),
                ),),
                  right: 0,top: 0,):Container()
              ],
            )
            ,

            // _otherItem(Constant.IMG_BASE+'me_kanjia.png','买家砍价'),
            _otherItem(Constant.IMG_BASE+'me_collect.png','我的收藏'),
            _otherItem(Constant.IMG_BASE+'me_goods.png','我的商品'),
          ],
        ),
        SizedBox(height: 20.h,),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            _otherItem(Constant.IMG_BASE+'me_liulan.png','浏览记录'),
            _otherItem(Constant.IMG_BASE+'me_tousu.png','投诉举报'),
            _otherItem(Constant.IMG_BASE+'me_help.png','帮助中心'),
            _otherItem(Constant.IMG_BASE+'me_renzheng.png','实名认证'),
          ],
        ),
        SizedBox(height: 20.h,),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            _otherItem(Constant.IMG_BASE+'me_invite.png','推广邀请'),
            _otherItem('',''),
            _otherItem('',''),
            _otherItem('',''),
          ],
        ),
      ],
    );
  }

  Widget _otherItem(img,name){
    return InkWell(
      onTap: (){
        if(name=='实名认证'){
          if(UserUtil.getUSER()!.idCard.isEmpty){
            Get.to(()=>RealNamePage())?.then((value) => {
              controller._getService()
            });
          }else{
            Get.to(()=>RealNamePage2())?.then((value) => {
              controller._getService()
            });
          }

        }else if(name=='我的收藏'){
          Get.to(()=>CollectionPage(),preventDuplicates:false);
        }else if(name=='浏览记录'){
          Get.to(()=>RecordsPage(),preventDuplicates:false);
        }else if(name=='我的商品'){
          Get.to(()=>OrdersSellPage(),arguments: 0,preventDuplicates:false);
        }else if(name=='投诉举报'){
          Get.to(()=>TousuPage());
        }else if(name=='帮助中心'){

          Get.to(()=>QAPage(),arguments: '帮助中心');
        }else if(name == '买家砍价'){
          Get.to(()=>PriceBuyerPage(),arguments: '买家砍价',preventDuplicates:false)?.then((value) => controller._messageLog());
        }else if(name == '我的砍价'){
          Get.to(()=>PriceMyPage(),arguments: '我的砍价',preventDuplicates:false)?.then((value) => controller._messageLog());
        }else if(name == '推广邀请'){
          Get.to(()=>InvitePage(),preventDuplicates:false);
        }
      },
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          img.isEmpty?Container(width: 46.w,height: 46.h):
          Image.asset(img,width: 46.w,height: 46.h,),
          SizedBox(height: 9.h,),
          Text(name,style: TextStyle(
              color: Color(0xFF333333),
              fontSize: 13.sp
          ),)
        ],
      )
    ) ;
  }

}